package cn.wolfcode.crm.shiro;

import cn.wolfcode.crm.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

@Component("crmFormAuthenticationFilter")
public class CRMFormAuthenticationFilter extends FormAuthenticationFilter {
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        //打印异常
        e.printStackTrace();
        String msg = "登录异常,请联系管理员";
        if (e instanceof UnknownAccountException) {
            msg = "账号错误";
        } else if (e instanceof IncorrectCredentialsException) {
            msg = "密码错误";
        }
        response.setContentType("text/json;charset=UTF-8");
        JsonResult result = new JsonResult(msg, false);
        try {
            response.getWriter().print(JSON.toJSONString(result));
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return false;//不放行
    }

    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().print(JSON.toJSONString(new JsonResult()));
        return false;//不放行
    }
}
